package com.jiuyou.clientController.mall.coupons;

import com.jiuyou.clientController.base.ClientBaseController;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.domain.model.LoginMember;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shopping.domain.*;
import com.ruoyi.shopping.service.*;
import lombok.val;
import org.apache.poi.ss.usermodel.IconMultiStateFormatting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.jaas.AbstractJaasAuthenticationProvider;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chengliang
 * @date 2022/6/27
 **/
@RestController
@RequestMapping("/client/mall/coupons")
public class MallCouponsClientController extends ClientBaseController {
    @Autowired
    private IMallCouponsService couponsService;
    @Autowired
    private IMallCouponsMemberService cmService;
    @Autowired
    private IMallProductSpecsService specsService;
    @Autowired
    private IMallProductService productService;
    @Autowired
    private IMallClassifyService classifyService;
    @Autowired
    private IMallCdkService cdkService;



    @RequestMapping("/getList")
    public AjaxResult getList() {
        MallCouponsMember cm = new MallCouponsMember();
        cm.setMemberId(cm.getMemberId());
        cmService.selectMallCouponsMemberList(cm);
        return AjaxResult.success();
    }

    @RequestMapping("/canUseList")
    public AjaxResult canUseList(@RequestBody List<CartVo> cartVos) {
        List<MallCouponsMember> result = cmService.canUseList(cartVos, getLoginMemberId());
        result=result.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<MallCouponsMember>(Comparator.comparing(MallCouponsMember::getId))),ArrayList::new));

        return AjaxResult.success(result);
}


    private List<MallCouponsMember> getMineCoupons(Long productId){

        MallCouponsMember mallCouponsMember = new MallCouponsMember();
        mallCouponsMember.setMemberId(getLoginMemberId());
        mallCouponsMember.setCanUseState(DicConstants.SYS_Y.getCode());
        mallCouponsMember.setUseState(DicConstants.SYS_N.getCode());
        MallProduct product = productService.selectMallProductById(productId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("classify",product.getClassifyId());
        map.put("product",product.getId());
        mallCouponsMember.setParams(map);
        mallCouponsMember.setCanUseState(DicConstants.SYS_Y.getCode());
        mallCouponsMember.setUseState(DicConstants.SYS_N.getCode());
//        mallCouponsMember.setMinPrice(product.getCurrentPrice());

//        List<MallCouponsMember> mallCouponsMembers = cmService.selectMineCoupons(mallCouponsMember);
        List<MallCouponsMember> mallCouponsMembers = cmService.selectCanUseList(mallCouponsMember);
        return mallCouponsMembers;
    }
    @PostMapping("/canReceive/{productId}")
    public AjaxResult canReceive(@PathVariable Long productId){
        MallProduct product = productService.selectMallProductById(productId);
        Long classifyId = product.getClassifyId();
        MallCoupons coupons = new MallCoupons();
//        coupons.setMinPrice(product.getCurrentPrice());
        coupons.setDistinctionCdkCoupon(DicConstants.DISTINCTION_COUPON.getCode());
        HashMap<String, Object> map = new HashMap<>(3);
        map.put("canReceive","Y");
        map.put("classifyId",classifyId);
        map.put("productId",productId);
        coupons.setParams(map);
        List<MallCoupons> list = couponsService.selectCanReceive(coupons);

        List<MallCouponsMember> mineCoupons = getMineCoupons(productId);

        HashMap<String, List> res = new HashMap<>(2);
        List<Long> collect = list.stream().map(MallCoupons::getId).collect(Collectors.toList());
        List<MallCouponsMember> received = cmService.selectByCouponId(collect,getLoginMemberId());
        List<Long> receivedCouponId = received.stream().map(MallCouponsMember::getCouponId).collect(Collectors.toList());
        Iterator<MallCoupons> iterator = list.iterator();
        while (iterator.hasNext()){
            MallCoupons next = iterator.next();
            if(receivedCouponId.contains(next.getId())){
                iterator.remove();
            }
        }
        res.put("canReceive",list);
        res.put("mine",mineCoupons);
//        res.put("mine",new ArrayList());

        return AjaxResult.success(res);
    }

    @PostMapping("/receive/{id}")
    public AjaxResult receive(@PathVariable Long id){
        MallCoupons coupons = couponsService.selectMallCouponsById(id);
        //检查是否是限量
        if(DicConstants.SYS_Y.getCode().equals(coupons.getLimitedState())){
            if(coupons.getLastTotal()<=0){
                return AjaxResult.success("优惠券被领取完了");
            }
        }
        if(DicConstants.SYS_Y.getCode().equals(coupons.getFixedTimeState())){
            if(coupons.getReceiveStartTime().compareTo(new Date()) >= 0 || coupons.getReceiveEndTime().compareTo(new Date()) <= 0) {
                return AjaxResult.success("未到领取时间或已过领取时间");
            }
        }
        MallCouponsMember cm = new MallCouponsMember();
        cm.setMemberId(getLoginMemberId());
        cm.setCouponId(coupons.getId());
        if(cmService.selectMallCouponsMemberList(cm).size()>0){
            return AjaxResult.success("已领取过该优惠券");
        }

        MallCouponsMember mallCouponsMember = new MallCouponsMember(coupons);
        Member loginMember = getLoginMember().getMember();
        mallCouponsMember.setMemberId(loginMember.getId());
        mallCouponsMember.setMemberNickname(loginMember.getNickName());
        mallCouponsMember.setMemberPhoto(loginMember.getHeadImg());
        mallCouponsMember.setReceiveType(DicConstants.RECEIVE_TYPE_Receive.getCode());
        if(DicConstants.SYS_Y.getCode().equals(coupons.getLimitedState())){
            coupons.setLastTotal(coupons.getLastTotal()-1);
            couponsService.updateMallCoupons(coupons);
        }
        cmService.insertMallCouponsMember(mallCouponsMember);
        return AjaxResult.success("success");
    }

    @PostMapping("/cdk/{cdk}")
    public AjaxResult cdk(@PathVariable String cdk){
        MallCdk cdkDo = cdkService.selectByCdk(cdk);
        if(cdkDo == null){
            return AjaxResult.error("该兑换码不可用");
        }
        if(DicConstants.SYS_Y.getCode().equals(cdkDo.getIfConversion())){
            return AjaxResult.error("该兑换码已用");
        }
        MallCoupons coupons = couponsService.selectMallCouponsById(cdkDo.getCouponId());
        if(DicConstants.SYS_Y.getCode().equals(coupons.getDelState())){
            return AjaxResult.error("该优惠券已停用");
        }
        Date date = new Date();
        if(DicConstants.SYS_N.getCode().equals(coupons.getFixedTimeState())){
            if(date.compareTo(coupons.getUseEndTime())>0){
                return AjaxResult.error("该优惠券已过期");
            }
        }

        ArrayList<Long> longs = new ArrayList<>();
        longs.add(cdkDo.getCouponId());
        List<MallCouponsMember> mallCouponsMembers = cmService.selectByCouponId(longs, getLoginMemberId());
        if(mallCouponsMembers.size()>0){
            return AjaxResult.error("您已领取/使用过该优惠券");
        }
//        MallCouponsMember couponsMember = new MallCouponsMember(coupons);
//        couponsMember.setMemberId(getLoginMemberId());
        MallCouponsMember mallCouponsMember = new MallCouponsMember(coupons);
        Member loginMember = getLoginMember().getMember();
        mallCouponsMember.setMemberId(loginMember.getId());
        mallCouponsMember.setMemberNickname(loginMember.getNickName());
        mallCouponsMember.setCdkey(cdk);
        mallCouponsMember.setMemberPhoto(loginMember.getHeadImg());
        mallCouponsMember.setReceiveType(DicConstants.RECEIVE_TYPE_CDK.getCode());
        cmService.insertMallCouponsMember(mallCouponsMember);
        cdkDo.setIfConversion(DicConstants.SYS_Y.getCode());
        cdkDo.setGetTime(date);
        cdkDo.setMemberId(mallCouponsMember.getMemberId());
        cdkService.updateMallCdk(cdkDo);
        return AjaxResult.success("领取成功");
    }

}
